package com.ma.gulimall.product.exception;

import com.ma.gulimall.exception.BizCodeEnume;
import com.ma.gulimall.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mayongqiang
 * @date 2021/8/6 15:32
 * @description 统一异常处理类
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.ma.gulimall.product.app")
//@ControllerAdvice(basePackages = "com.ma.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    /**
     * 特定·异常处理
     * 一开始不知具体异常信息，直接使用Exception e
     * 测试打印获得具体异常
     *
     * 参数非法（校验参数）异常 MethodArgumentNotValidException
     * */

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){

        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errMap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((fieldError)->{
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg())
                .put("data",errMap);
    }


    //其余异常处理
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误异常{}",throwable);

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }


}
